<?php

namespace forfun\service;

use forfun\constant\ErrorCode;
use forfun\context\CoreContext;
use forfun\controller\vo\WeirdForm;
use forfun\exception\ForFunException;
use forfun\repository\AgreeRecordRepository;
use forfun\repository\entity\AgreeRecord;
use forfun\repository\entity\Comment;
use forfun\repository\entity\Weird;
use forfun\repository\UserRepository;
use forfun\repository\WeirdRepository;
use restphp\biz\PageParam;
use restphp\utils\RestStringUtils;

class WeirdService {
    /**
     * 获取列表.
     * @param $key
     * @param $page
     * @param $range
     * @return array
     */
    public static function getWeirdList($key, $page, $range) {
        $weirdRepository = new WeirdRepository();
        $queryRule = array(
            'rule' => array(
                'state' => array("(state=2 or (state in (0,1) and user_id=:user_id))", array('user_id'=>CoreContext::getUser()->getId()))
            ),
            'page_param' => PageParam::getInstance($page, APP_DATA_LIST_PAGE_SIZE),
            'order' => ' order by id desc'
        );
        if (!RestStringUtils::isBlank($key)) {
            $queryRule['rule']['title'] = array('title like :title', array('title'=>"%$key%"));
        }
        if ($range == 1) {
            $queryRule['rule']['user_id'] = CoreContext::getUser()->getId();
        }
        $weirdList = $weirdRepository->select($queryRule, false);
        $arrIds = array();
        foreach ($weirdList as $weird) {
            $arrIds[] = $weird['user_id'];
        }
        if (empty($weirdList)) {
            return $weirdList;
        }

        $userNameMap = UserService::getUsernameMapByIds($arrIds);

        foreach ($weirdList as &$weird) {
            $weird['user_name'] = $userNameMap[$weird['user_id']];
            $weird['is_owner'] = ($weird['user_id'] == CoreContext::getUser()->getId()) ? 1 : 0;
            $weird['had_agree'] = 0;
            $weird['agree_number'] = 0;
        }

        return $weirdList;
    }

    /**
     * 添加奇闻.
     * @param WeirdForm $weirdForm
     * @return void
     */
    public static function add($weirdForm) {
        $weirdRepository = new WeirdRepository();
        $max = $weirdRepository->countRule(array(
            'user_id' => CoreContext::getUser()->getId(),
            'create_time' => array('create_time > :create_time', array('create_time'=>date('Y-m-d') . ' 00:00:00'))
        ));
        if ($max >= APP_WEIRD_MAX_ADD_ONE_DAY) {
            throw new ForFunException(ErrorCode::WEIRD_OVER_MAX_LIMIT_ONE_DAY);
        }

        $weird = new Weird();
        $weird->setUserId(CoreContext::getUser()->getId());
        $weird->setTitle($weirdForm->getTitle());
        $weird->setCreateTime(date('Y-m-d H:i:s'));
        $weird->setContent($weirdForm->getContent());
        $weird->setUpdateTime(date('Y-m-d H:i:s'));
        $weird->setFavourNumber(0);
        $weird->setCommentNumber(0);
        $weird->setState(Weird::STATE_PUBLISHED);
        $weirdRepository->save($weird);
    }

    /**
     * @param int $id
     * @param WeirdForm $weirdForm
     * @return void
     */
    public static function modify($id, $weirdForm) {
        $weirdRepository = new WeirdRepository();
        $weird = $weirdRepository->findOneById($id);
        if (empty($weird) || $weird->getUserId() != CoreContext::getUser()->getId()) {
            throw new ForFunException(ErrorCode::WEIRD_NOT_EXIST);
        }

        $weird->setTitle($weirdForm->getTitle());
        $weird->setContent($weirdForm->getContent());
        $weird->setUpdateTime(date('Y-m-d H:i:s'));
        $weirdRepository->save($weird);
    }

    /**
     * 删除.
     * @param $id
     * @return void
     */
    public static function delete($id) {
        $weirdRepository = new WeirdRepository();
        $weird = $weirdRepository->findOneById($id);
        if (empty($weird) || $weird->getUserId() != CoreContext::getUser()->getId()) {
            throw new ForFunException(ErrorCode::WEIRD_NOT_EXIST);
        }
        $weird->setState(Weird::STATE_DELETED);
        $weirdRepository->save($weird);
    }

    /**
     * 点赞.
     * @param int $id
     * @return void
     */
    public static function addFavour($id) {
        $weirdRepository = new WeirdRepository();
        $weird = $weirdRepository->findOneById($id);
        if (null == $weird) {
            throw new ForFunException(ErrorCode::WEIRD_NOT_EXIST);
        }
        $agreeRecordRepository = new AgreeRecordRepository();
        $agreeRecord = $agreeRecordRepository->getAgreeRecord(CoreContext::getUser()->getId(), AgreeRecord::TYPE_WEIRD, $id);
        if (null != $agreeRecord) {
            throw new ForFunException(ErrorCode::COMMON_HAD_AGREE);
        }
        $agreeRecordRepository->pUpdateDB()->startTran();
        $agreeRecordRepository->addFavour(CoreContext::getUser()->getId(), AgreeRecord::TYPE_WEIRD, $id);
        $weird->setFavourNumber($weird->getFavourNumber() + 1);
        $weirdRepository->save($weird);
        $agreeRecordRepository->pUpdateDB()->commitTran();
    }

    public static function addComment($id, $comment) {
        $weirdRepository = new WeirdRepository();
        $weird = $weirdRepository->findOneById($id);
        if (null == $weird) {
            throw new ForFunException(ErrorCode::WEIRD_NOT_EXIST);
        }
        $weirdRepository->pUpdateDB()->startTran();
        CommentService::addComment(Comment::KIND_WEIRD, $id, $comment);
        $weird->setCommentNumber($weird->getCommentNumber() + 1);
        $weirdRepository->save($weird);
        $weirdRepository->pUpdateDB()->commitTran();
    }
}